package corejava2;


//import javafx.util.Pair;

import java.util.*;

//统计一句话中每一个单词出现的次数，并按照出现次数从多到少排序，相同的次数用字典排序
class Pair<T1, T2> {
    T1 key;

    public Pair(T1 word, T2 integer) {
        key = word;
        value = integer;

    }

    public T1 getKey() {
        return key;
    }

    public void setKey(T1 key) {
        this.key = key;
    }

    public T2 getValue() {
        return value;
    }

    public void setValue(T2 value) {
        this.value = value;
    }

    T2 value;

}

public class Exp04WordsCounter2 {
    public static void main(String[] args) {
        String line = "To  know  everything is to know   nothing.";
        Map<String, Integer> map = new TreeMap<String, Integer>();
        System.out.println(line = line.toLowerCase().replaceAll("[^a-zA-z]", " ").trim());
        System.out.println(line);//
        String[] words = line.split("\\s+");
        System.out.println(Arrays.toString(words));
        for (String word : words) {
            if (map.containsKey(word)) {
                int old = map.get(word);
                map.put(word, old + 1);
            } else {
                map.put(word, 1);
            }
        }
        System.out.println(map);


        Queue<Pair<String, Integer>> q = new PriorityQueue<>(
                (o1, o2) -> {
                    if (!o1.getValue().equals(o2.getValue())) {
                        return o2.getValue() - o1.getValue();
                    }
                    return o1.getKey().compareTo(o2.getKey());
                }
        );
        for (String word : map.keySet()) {
            q.offer(new Pair<>(word, map.get(word)));
        }
        for (int i = 0; i < 10 && !q.isEmpty(); i++) {
            System.out.println(q.peek().getKey() + "-----" + q.peek().getValue());
            q.poll();
        }


    }
}
